// controller/LoginController.java
package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.UserPojo;
import com.lei.springbootpractice.service.UserService;
import com.lei.springbootpractice.service.CategoryCacheManager;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

    private final UserService userService;
    
    @Autowired
    private CategoryCacheManager cacheManager;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    // 添加明确的视图解析指令
    @GetMapping("/login")
    public ModelAndView showLoginForm() {
        return new ModelAndView("login"); // 显式指定视图对象
    }


    @PostMapping("/login")
    public String login(@RequestParam String userID,
                        @RequestParam String password,
                        HttpSession session,
                        Model model) {
        UserPojo user = userService.validateLogin(userID, password);
        if (user != null) {
            session.setAttribute("loggedInUser", userID);
            session.setAttribute("userRole", user.getRole());

            // 登录成功时刷新分类缓存，确保用户能看到最新的分类数据
            System.out.println("用户登录成功，刷新分类缓存");
            cacheManager.refreshCacheNow();

            // 根据角色跳转
            return switch (user.getRole()) {
                case "super_admin", "admin" -> "redirect:/admin/dashboard";
                case "customer_service" -> "redirect:/customer-service/dashboard";
                default -> "redirect:/customer/dashboard";
            };
        } else {
            model.addAttribute("error", "账号或密码错误");
            return "login";
        }
    }

    @GetMapping("/welcome")
    public String welcome(HttpSession session, Model model) {
        // 从会话中获取用户信息
        String userID = (String) session.getAttribute("loggedInUser");

        // 查询用户详细信息
        UserPojo user = userService.getUserByUserID(userID);

        // 传递数据到模板
        model.addAttribute("username", user.getUserName());
        return "welcome";
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 清除会话
        session.invalidate();
        return "redirect:/login?logout=true";
    }
    
    @GetMapping("/test-users")
    public String testUsers() {
        return "test-users";
    }
}
